from gm.api import *
import numpy as np
import talib


def init(context):
    '''   主程序初始化    '''
    # context.symbol = 'SZSE.300296'# 利亚德
    context.symbol = 'SZSE.000425'# 徐工
    context.frequency = '1d'
    context.fields = 'open,high,low,close'
    context.volume = 100

    schedule(schedule_func=algo, date_rule='1d', time_rule='09:35:00')


def algo(context):
    now = context.now
    last_day = get_previous_trading_date('SZSE', now)
    data = history_n(symbol=context.symbol,
                     frequency=context.frequency,
                     count=35,
                     end_time=now,
                     fields=context.fields,
                     fill_missing='last',
                     adjust=ADJUST_PREV,
                     df=True,
                     )
    open = np.asarray((data['open'].values))
    high = np.asarray((data['high'].values))
    low = np.asarray((data['low'].values))
    close = np.asarray((data['close'].values))

    ma = talib.MA(close, timeperiod=5)
    ma2 = talib.MA(close, timeperiod=30)
    # print(ma, ma2)
    macd, macd2 = ma[-1], ma2[-1]
    连续 = ma[-16:]
    连涨指数_ = 0
    连跌指数_ = 0
    a = 0
    for i in 连续:
        if i > a:
            连涨指数_ += 1
        else:
            连跌指数_ += 1
        a = i
    print('len(MA):', len(ma), 连涨指数_, 连跌指数_, '*' * 20)
    macd = macd2 - macd
    print(macd)

    if 连跌指数_ > 10:
        order_volume(symbol=context.symbol,
                     volume=context.volume,
                     side=PositionSide_Long,
                     order_type=OrderType_Market,
                     position_effect=PositionEffect_Open,
                     )
        print('买入', )
    elif 连涨指数_ > 10:
        order_volume(symbol=context.symbol,
                     volume=context.volume,
                     side=PositionSide_Short,
                     order_type=OrderType_Market,
                     position_effect=PositionEffect_Close
                     )
        print('卖出')


if __name__ == '__main__':
    run(
        strategy_id='a5299b24-8b44-11e9-a4d4-b499baf0193a',
        filename='程序5_9连续涨跌查找策略.py',
        mode=MODE_BACKTEST,
        token='90be3f863b23ab3c1ef68d1f9b8dc06e4bebb30d',
        backtest_start_time='2006-01-01 09:00:00',
        backtest_end_time='2017-12-31 15:00:00',
        backtest_initial_cash=10000,
        backtest_adjust=ADJUST_PREV,
    )
